package com.xxxx.server.controller;
import com.xxxx.server.pojo.FastDFSFile;
import com.xxxx.server.utils.FastDFSClient;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import java.io.InputStream;

@Controller
public class testfile {
    @PostMapping("/upload")
    public String Fileupload(@RequestParam MultipartFile file, RedirectAttributes redirectAttributes) throws Exception {
        if (file.isEmpty()){
            redirectAttributes.addFlashAttribute("message","请选择一个文件上传");
            return "redirect:/uploadStatus";
        }
        String path=saveFile(file);
        redirectAttributes.addFlashAttribute("message","文件上传成功"+file.getOriginalFilename());
        redirectAttributes.addFlashAttribute("path","路径"+path);
        return "redirect:/";
    }
@GetMapping("/uploadStatus")
public String up(){
        return "sc";
}
    @GetMapping("/")
    public String jg() {
        return "jg";
    }

        public String saveFile(MultipartFile multipartFile) throws Exception {
        String[] fileAbsolutePath={};
        String fileName=multipartFile.getOriginalFilename();
        String ext =fileName.substring(fileName.lastIndexOf(".")+1);
        byte[] file_buff =null;
        InputStream inputStream =multipartFile.getInputStream();
        if(inputStream!=null){
            int len1 =inputStream.available();
            file_buff=new byte[len1];
            inputStream.read(file_buff);
        }
        inputStream.close();
        FastDFSFile  file = new FastDFSFile(fileName,file_buff,ext);//error
        fileAbsolutePath=FastDFSClient.upload(file);
        if (fileAbsolutePath==null){
            System.out.println("上传失败");
        }
        String path =FastDFSClient.getTrackerUrl()+fileAbsolutePath[0]+"/"+fileAbsolutePath[1];
        return path;
    }
}
